<?php

namespace Modules\Basic\Http\Controllers;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
use Modules\Basic\Models\Users;

class LoginController
{
    /**
     * 登录验证并生成token
     *
     * @param Request $request
     * @return array|\Illuminate\Http\JsonResponse
     * @throws ValidationException
     */
    function index(Request $request)
    {

        /* @var Users $users */
        $users = Users::query()->where('name', $request->get('username'))->first();

        if ($users) {
            if ($users->is_disabled == '是') {
                throw ValidationException::withMessages([
                    'username' => ['账户被禁用'],
                ]);
            }
            if (Hash::check($request->get('password'), $users->password)) {
                $token = $users->createToken('token')->plainTextToken;
                return response()->json([
                    'success' => true,
                    'message' => '登录成功'
                ]);
                    //compact('token');
            }
        }
        throw ValidationException::withMessages([
            'username' => ['用户名或密码错误'],
        ]);
    }

    /**
     * 用户注册
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    function register(Request $request)
    {
        $users = Users::create([
            'name' => $request->get('username'),
            'password' => Hash::make($request->get('password')),
            'email' => $request->get('email'),
        ]);
        return response()->json([
            'success' => true,
            'message' => '注册成功'
        ]);
    }


}
